// pages/index/applyBox.js
var App = getApp();
var openId = '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    username:'',
    nameErrorTip:false,

    provice:'',
    proviceId:'',
    city:'',
    cityId:'',

    school:'',
    schoolId:'',
    schoolErrorTip:false,

    house:'',
    houseId:'',
    dormitory:'',
    dormitoryId:'',
    dormitoryErrorTip:false,

    listShow:false,
    alertList:[],
    tempProvice:{},//选择的省份
    tempCity: {},//选择的城市
    tempSchool:{},
    tempHouse:{},
    tempFloor: {},
    current: 1, //1表示当前显示的是省
    scrollTop:0,
    showPop: false, //是否显示弹窗
    promoteCode:'', //高校端注册码
    hasBoxId: '', //是否是有盒子信息来的注册
    fromCloud: false,
    hasPhone: false,// 是否完善了手机号
    showAgreement: false,
    agreeContent:'',
    showApplyStep: true //显示申领步骤
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.agreementContent();//申领协议
    wx.showLoading({
      title: '加载中',
    })
    if (options.source == 'cloud'){
      this.setData({
        fromCloud: true,
        showApplyStep: false,
        hasPhone: wx.getStorageSync('userInfo').phone=='0'?false:true
      })
    }
    
    //高校端扫码直接注册
    if (options.q) {
      let qrUrl = decodeURIComponent(options.q);//获取二维码的携带的链接信
      if (qrUrl.indexOf('promoteCode') > -1) {
        this.setData({
          promoteCode: qrUrl.split('=')[1]
        })      
      } else if (qrUrl.indexOf('boxId') > -1){//有盒子信息的
        this.setData({
          hasBoxId: options.boxId
        })
      }
      this.getWxUserOpenid();//获取用户token
    }else if(options.boxId){// 菜单栏扫码进来的
      this.setData({
        hasBoxId: options.boxId
      })
      this.getUserApplyMsg();
    }
    else{
      // 自动定位
      this.getUserLocation();
    }
  },
  //获取盒子携带的信息信息
  getUserApplyMsg: function () {
    const that = this;
    wx.request({
      url: App.data.globalAPI + '/box/attr/getinfo', //接口地址
      data: {
        token: wx.getStorageSync('token'),
        box_id: that.data.hasBoxId
      },
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        if (res.data.error == 0) {
          let array = res.data.data;
          console.log(array)
          that.setData({
            proviceId: array.province_id,
            cityId: array.city_id,
            school: array.school,
            schoolId: array.school_id,
            house: array.floor,
            houseId: array.floor_id,
            dormitory: array.floor + '-' + array.hostel,
            dormitoryId: array.hostel_id,
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
        wx.hideLoading();
      },fail(){
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
        that.setData({
          noNetwork: true
        }) 
      }
    })
  },

  //定位
  getUserLocation:function(){
    const that = this;
    const locationStr = wx.getStorageSync('location');
    if (locationStr != ''){
      wx.request({
        url: App.data.globalAPI + '/search/index/nearestschool',
        data: {
          token: wx.getStorageSync('token'),
          location: wx.getStorageSync('location'), //经度在前，纬度在后
          type: 'gps'
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res2) {
          const nearest = res2.data.data.nearest;
          const floors = res2.data.data.floors;
          if (res2.data.error == 0) {
            if (nearest.name == null) {
              wx.showToast({
                title: '当前城市暂无开通学校',
                icon: 'none',
                duration: 1500
              })
            } else {
              that.setData({
                provice: nearest.province,
                proviceId: nearest.province_id,
                city: nearest.city,
                cityId: nearest.city_id,
                school: nearest.name,
                schoolId: nearest.id,
                alertList: floors
              })
            }

          } else {
            wx.showToast({
              title: '数据异常，请检查您的定位信息及网络状态稍后再试',
              icon: 'none'
            })
          }
          wx.hideLoading();
        },fail(){
          wx.hideLoading()
          wx.showModal({
            title: '提示',
            content: '网络异常，请稍后重试！',
            showCancel: false,
            success(res) {
            }
          })
          that.setData({
            noNetwork: true
          }) 
        }
      })
    }else{
      wx.hideLoading();
      wx.getLocation({
        type: 'wgs84',
        success(res) {
          const latitude = res.latitude //纬度
          const longitude = res.longitude //经度
          const accuracy = res.accuracy;
          let locateStr = longitude + ',' + latitude;//经度在前，纬度在后
          wx.showLoading({
            title: '定位中',
          })
          wx.setStorageSync('location', locateStr)
          wx.setStorageSync('latitude', latitude);
          wx.setStorageSync('longitude', longitude);
          that.getUserLocation();
        }, fail() {
          wx.showToast({
            icon: 'none',
            title: '定位失败'
          })
        }
      })
    }
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },


  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.removeStorageSync('applyStatus');
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //back
  backLastPage: function () {
    if (this.data.promoteCode != '' || this.data.hasBoxId != '' ){
      wx.reLaunch({
        url: '/pages/index/index',
      })
    }else{
      wx.navigateBack({
        delta: 1
      })
    }
  },
  // bind username
  nameInput:function(e){
    this.setData({
      nameErrorTip:false,
      username: e.detail.value
    })
  },
  stopHandle:function(){
    return false;
  },
  //学校选择
  onSchoolHandle:function(){
    let that = this;
    if (that.data.promoteCode != '' || that.data.hasBoxId != ''){
      return false;
    }
    if(that.data.school==''){ //，没有定位的学校
      that.setData({
        listShow: true,
        current: 1,
        tempProvice: {},//选择的省份
        tempCity: {},//选择的城市
        tempSchool: {},
      })
      that.loadProviceData('');
    }else{
      that.setData({
        listShow: true,
        current: 3,
        tempProvice: {id:that.data.proviceId, name:that.data.provice},//选择的省份
        tempCity: { id: that.data.cityId, name: that.data.city},//选择的城市
        tempSchool: { id: that.data.schoolId, name: that.data.school},
      })
      that.loadOtherList(that.data.cityId, '', '');
    }
    
  },
  //省份搜索
  loadProviceData:function(pId){
    let that = this;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: App.data.globalAPI + '/search/index/city',
      data: {
        token: wx.getStorageSync('token'),
        pid: pId,
        name: ''
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        const arr = res.data;
        if (arr.error == 0) {
          that.setData({
            alertList: arr.data
          })
        } else {
          wx.showToast({
            title: '数据异常，请检查您的定位信息及网络状态稍后再试',
            icon: 'none'
          })
        }
      },complete(){
        wx.hideLoading();
      }
    })
  },
  // 宿舍选择
  onHouseHandle:function(){
    if (this.data.promoteCode != '' || this.data.hasBoxId != '') {//高校端来的禁止修改
      return false;
    }
    if (this.data.school == ''){
      wx.showToast({
        title: '请先选择学校',
        icon:'none',
        duration:800
      })
    } else {
      if(this.data.dormitory==''){//没有选择过宿舍
        this.setData({
          tempHouse: {},
          tempFloor: {},
          listShow: true,
          current: 4,
          scrollTop: 0
        })
        this.loadOtherList(this.data.cityId, this.data.schoolId, '');  
      }else{
        this.setData({
          tempHouse: {id: this.data.houseId, name: this.data.house},
          tempFloor: {id:this.data.dormitoryId, name: this.data.dormitory.split('-')[1]},
          listShow: true,
          current: 5,
          scrollTop: 0
        })
        this.loadOtherList(this.data.cityId, this.data.schoolId, this.data.houseId);  
      }
       
    }
  },
  //选择信息
  chosedMsg:function(e){
    let index = this.data.current;
    let value = e.currentTarget.dataset.value;
    let that = this;
    that.setData({
      scrollTop:0
    })

    switch(index){
      case 1:
        that.setData({
          tempProvice: value,
          current:2
        })
        that.loadProviceData(that.data.tempProvice.id);
        break;
      case 2:
        that.setData({
          tempCity: value,
          current:3
        })
        that.loadOtherList(that.data.tempCity.id, '', '');
        break;
      case 3:
        if(that.data.school != value.name){
          that.setData({
            house: '',
            houseId: '',
            dormitory: '',
            dormitoryId: '',
          })
        }
        that.setData({
          tempSchool: value,
          provice: that.data.tempProvice.name,
          proviceId: that.data.tempProvice.id,
          city: that.data.tempCity.name,
          cityId: that.data.tempCity.id,
          school: value.name,
          schoolId: value.id,
          listShow: false,
          current:4,
          alertList: [],
        })
        break;
      case 4:
        that.setData({
          tempHouse: value,
          current:5
        })
        that.loadOtherList(that.data.cityId, that.data.schoolId, that.data.tempHouse.id);
        break;
      case 5:
        that.setData({
          tempHouse: value,
          house: that.data.tempHouse.name,
          houseId: that.data.tempHouse.id,
          dormitory: that.data.tempHouse.name+'-'+value.name,
          dormitoryId: value.id,
          listShow: false,
        })
        break;
      default:
    }
  },
  //省份选择
  choseProvince:function(){
    this.setData({
      current:1,
      tempProvice: {},//选择的省份
      tempCity: {},
      tempSchool: {},
      alertList: [],
    })
    this.loadProviceData('');
  },
  //城市选择
  choseCity: function () {
    this.setData({
      current: 2,
      tempCity: {},
      tempSchool: {},
      alertList: [],
    })
    this.loadProviceData(this.data.tempProvice.id);
  },
  // 宿舍选择
  choseHouse:function(){
    this.setData({
      tempHouse: {},
      tempFloor: {},
      listShow: true,
      current: 4
    })
    this.loadOtherList(this.data.cityId, this.data.schoolId, '');  
  },
  
  // 提交用户信息
  commitUserMsg:function(){
    // console.log(this.data.username, this.data.provice, this.data.city, this.data.school, this.data.house, this.data.dormitory)
    // return false;
    this.setData({
      nameErrorTip: false,
      schoolErrorTip: false,
      dormitoryErrorTip: false
    })

    if (this.data.username == ''){
      this.setData({
        nameErrorTip:true
      })
    }
    if (this.data.school == '') {
      this.setData({
        schoolErrorTip: true
      })
    }
    if (this.data.dormitory == '') {
      this.setData({
        dormitoryErrorTip: true
      })
    }
    if (this.data.nameErrorTip || this.data.schoolErrorTip || this.data.dormitoryErrorTip){
        wx.showToast({
          title: '小主，您的资料还没有完善哦',
          icon: 'none',
          duration: 800
        })
    }
    else{
      //高校端注册来源信息
      this.uploadUserMsg();     
    }

  },
  
  //学校楼宿舍列表
  loadOtherList: function (cityId,sId, fId) {
    let that = this;
    that.setData({
      alertList:[]
    })
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: App.data.globalAPI + '/search/index/belong',
      data: {
        token: wx.getStorageSync('token'),
        name: '',
        city_id: cityId,
        school_id: sId,
        floor_id: fId
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        const arr = res.data;
        if (arr.error == 0) {
          //sId,fId为空时表示请求的s是学校，fId为空时表示请求的s是楼栋，都不为空是宿舍
          that.setData({
            alertList: arr.data
          })
        } else {
          wx.showToast({
            title: '数据异常，请检查您的定位信息及网络状态稍后再试',
            icon: 'none'
          })
        }
      },fail(){
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      },complete() {
        wx.hideLoading();
      }
    })
  },
  //提交用户信息接口
  uploadUserMsg:function(){
    let that = this; 

    wx.request({
      url: App.data.globalAPI + '/users/user/perfect',
      data: {
        token: wx.getStorageSync('token'),
        nickname: that.data.username,
        province_id: that.data.proviceId,
        city_id: that.data.cityId,
        school_id: that.data.schoolId,
        school_name: that.data.school,
        floor_id: that.data.houseId,
        floor_name: that.data.house,
        hostel_id: that.data.dormitoryId,
        hostel_name: that.data.dormitory.split('-')[1],
        box_id: that.data.hasBoxId
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        const arr = res.data;
        if (arr.error == 0) {
          if (that.data.fromCloud){ //云库的完善信息
            let info = wx.getStorageSync('userInfo');
            let userMsg = wx.getStorageSync('allUserMsg');
            info.nickname = that.data.username;
            info.province_id = that.data.proviceId;
            info.city_id = that.data.cityId;
            info.school_id = that.data.schoolId;
            info.floor_id = that.data.houseId;
            info.hostel_id = that.data.dormitoryId;
            userMsg.userinfo = info;

            wx.setStorageSync('userInfo', info);
            wx.setStorageSync('allUserMsg', userMsg)
            let page = getCurrentPages();
            var last = page[page.length - 2];
            last.setData({
              userMsgIsAll: true,
              phone: wx.getStorageSync('userInfo').phone,
              username: that.data.username,
              address: that.data.school + that.data.house + ' ' + that.data.dormitory.split('-')[1]
            })
            wx.showToast({
              title: '信息提交成功！',
              icon: 'none'
            })
            setTimeout(function () {
              wx.navigateBack({
                detal: 1
              })
            }, 600)
            return false;
          }

          wx.setStorageSync('applyStatus', arr.data.status);  
                 
          if(arr.data.status == -1){
            if(that.data.promoteCode!=''){
              that.goSupplyPage();//判断补货是否开启
              return false;
            }
          } else if (arr.data.status == 0) {
            wx.showToast({
              title: '小主，您可爱的舍友已经申请过啦',
              icon: 'none',
              duration: 1000
            })
            setTimeout(function () {
              wx.redirectTo({
                url: '/pages/index/index?boxId=' + arr.data.box_id,
              })
            }, 1000)
          } else {
            if (that.data.hasBoxId != ''){ //有盒子信息
              wx.showToast({
                title: '您已成功认领盒子，快去补货吧！',
                icon: 'none',
                duration: 1000
              })
            }else{
              wx.showToast({
                title: '您的申请已提交，补货后才算认领成功哦！',
                icon: 'none',
                duration: 1000
              })
            }
            let page = getCurrentPages();
            var last = page[page.length - 2];
            last.getTokenLogin();  
            that.goSupplyPage();//判断补货是否开启       
          } 
        }else{
          wx.showToast({
            title: arr.msg,
            icon: 'none',
            duration: 800
          })
        }
      }
    })
  },
  //直接审核通过更新用户信息
  getWxUserinfo: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/users/login/login',
      data: {
        openid: openId,
        token: wx.getStorageSync('token')
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.error == 0) {
          wx.setStorageSync('token', res.data.data.token);
          wx.setStorageSync('userInfo', res.data.data.userinfo);
          wx.setStorageSync('allUserMsg', res.data.data);

          if (that.data.hasBoxId!='') {//有盒子信息的
            that.getUserApplyMsg();
          }
        }
      }
    })
  },
  onHideAlert:function(){
    this.setData({
      listShow: false
    })
  },

  //获取用户的openid
  getWxUserOpenid: function () {
    const that = this;
    wx.login({
      success: function (res) {
        //发送请求
        wx.request({
          url: App.data.globalAPI + '/users/weixin/login', //接口地址
          data: {
            code: res.code,
            source: 'small program',//注册来源标识
            invite_id: ''//邀请人标识
          },
          header: {
            'content-type': 'application/json' //默认值
          },
          success: function (res) {
            if (res.data.error == 0) {
              wx.hideLoading();
              wx.setStorageSync('token', res.data.data.token);
              wx.setStorageSync('userInfo', res.data.data.userinfo);
              wx.setStorageSync('allUserMsg', res.data.data);

              if (wx.getStorageSync('userInfo').hostel_id != null){
                wx.showToast({
                  title: '您已经申领过盒子了',
                  icon:'none'
                })
                setTimeout(function(){
                  wx.reLaunch({
                    url: '/pages/index/index',
                  })
                },800)
              }else{
                that.getApplyCodeMsg();
              }
 
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none'
              })
            }
          }
        })
      }, fail(res) {
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {

          }
        })
      }
    })
  },
  //获取得到的学校信息
  getApplyCodeMsg:function(){
    const that = this;
    wx.request({
      url: App.data.globalAPI + '/agent/promote/applyinfo', //接口地址
      data: {
        token: wx.getStorageSync('token'),
        promoteCode: that.data.promoteCode
      },
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        if (res.data.error == 0) {
          let array = res.data.data;
          that.setData({
            proviceId: array.province_id,
            cityId: array.city_id,
            school: array.school,
            schoolId: array.school_id,
            house: array.floor,
            houseId: array.floor_id,
            dormitory: array.floor+'-'+array.hostel,
            dormitoryId: array.hostel_id,
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },

  //申请盒子手机号判断
  bindApplyBox: function (e) {
    let that = this;
    if (e.detail.errMsg == 'getPhoneNumber:ok') {//同意手机号授权
      wx.request({
        url: App.data.globalAPI + '/users/weixin/decrypt',
        data: {
          token: wx.getStorageSync('token'),
          data: e.detail.encryptedData,
          iv: e.detail.iv
        },
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success(res) {
          if (res.data.error == 0) {
            var myphone = JSON.parse(res.data.data).phoneNumber;

            let userInfo = wx.getStorageSync('userInfo');
            let allUserMsg = wx.getStorageSync('allUserMsg');
            userInfo.phone = myphone;
            allUserMsg.userinfo = userInfo;
            wx.setStorageSync('userInfo', userInfo);
            wx.setStorageSync('allUserMsg', allUserMsg);

            that.commitUserPhone();
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 800
            })
          }
        }
      })
    }

  },

  //提交用户手机
  commitUserPhone: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/users/user/bindphone',
      data: {
        token: wx.getStorageSync('token'),
        phone: wx.getStorageSync('userInfo').phone,
        validate_code: '0000',
        is_activity: 0
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success(res) {
        const arr = res.data;
        if (arr.error != 0) {
          wx.showToast({
            title: arr.msg,
            icon: 'none',
            duration: 800
          })
        }
        that.uploadUserMsg(); 

        // if (App.data.locationIsActive) {//是参加活动的地区
        //   wx.showToast({
        //     title: '优惠券发放成功请到券包查看',
        //     icon: 'none',
        //     duration: 800
        //   })
        //   setTimeout(function () {
        //     wx.navigateTo({
        //       url: '/pages/index/new_user_active',
        //     })
        //   }, 600)
        // }
      }
    })
  },

  // 去补货页面
  goSupplyPage: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/mall/goods/getyunbuystatus', //接口地址
      data: {
        token: wx.getStorageSync('token'),
        school_id: wx.getStorageSync('userInfo').school_id
      },
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        if (res.data.error == 0) {
          if (res.data.data.supply_status == 1) {
            setTimeout(function () {
              wx.redirectTo({
                url: '/pages/index/replenishment/buhuo',
              })
            }, 800)   
          } else {
            wx.showToast({
              title: '补货商城暂未开启',
              icon: 'none'
            })
            setTimeout(function () {
              wx.navigateBack({
                detal: 1
              })
            }, 800)  
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }, fail(res) {
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      },
    })
  },

  //显示申领协议
  showAgreeHandle:function(){
    this.setData({
      showAgreement: !this.data.showAgreement
    })
  },

  agreementContent:function(){
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/application_agreement.html', //接口地址
      data: {
   
      },
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        that.setData({
          agreeContent: res.data
        })
      }, fail(res) {
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      },
    })
  }

})